package logic;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import org.supercsv.io.CsvMapWriter;
import org.supercsv.io.ICsvMapWriter;
import org.supercsv.prefs.CsvPreference;

import com.github.mhendred.face4j.exception.FaceClientException;
import com.github.mhendred.face4j.exception.FaceServerException;

public class Teste {
	
	public static String pathImages;
	public static String pathOut;
	public static String pathCSV;
	
	public static void main(String[] args) throws IOException {
		
		pathImages = "C:\\Users\\Delano\\Pictures\\new_test";
		pathOut = "C:\\Users\\Delano\\Pictures\\out.txt";
		pathCSV = "C:\\Users\\Delano\\Pictures\\resultados.csv";
	
		File pathFolderImages = new File(pathImages);
		BufferedWriter out = new BufferedWriter(new FileWriter(new File(pathOut)));
		
		LogicFace logicFace = LogicFace.getInstance("f1454d2b088878a684ee6ed43ceb3055",
				"d2f88bed9cd6485ae94ad5791885d62c");
		
		logicFace.setPathCSV("C:\\Users\\Delano\\Pictures\\DBImages.csv");
		logicFace.setPathImages("C:\\Users\\Delano\\Pictures\\new");
		
		File file = new File(pathCSV);
		file.createNewFile();
		FileWriter fileWriter = new FileWriter(file.getAbsolutePath());
		ICsvMapWriter writer = new CsvMapWriter(fileWriter,
				CsvPreference.EXCEL_NORTH_EUROPE_PREFERENCE);

		String[] header = new String[] { "Cartoon", "Precision", "Similarity"};

		writer.writeHeader(header);
		
		HashMap<String, String> data = new HashMap<String, String>();

		
		for(File f : pathFolderImages.listFiles()){
			try {
				Score score = logicFace.searchFace(f);
				
				List<ScoreElement> l = score.list();
				
				out.write(f.getName());
				out.newLine();
				out.write("1 - " + score.first());
				out.newLine();
				
				for(int i = 0; i < l.size(); i++){
					ScoreElement element = l.get(i);
					if(f.getName().contains(element.name)){
						out.write((i+1) + " - " + l.get(i));
						out.newLine();
						data.put(header[0], f.getName());
						data.put(header[1], fixNumber(100 - (i * 100.0/l.size()) + ""));
						data.put(header[2], fixNumber(element.value.toString()));
						
						writer.write(data, header);
					}
				}
				
			} catch (FaceClientException e) {
				out.write("ERRO - " + f.getName());
				out.newLine();
				e.printStackTrace();
			} catch (FaceServerException e) {
				out.write("ERRO - " + f.getName());
				out.newLine();
				e.printStackTrace();
			} catch (NullPointerException e) {
				out.write("ERRO - " + f.getName());
				out.newLine();
				e.printStackTrace();
			}
		}
		out.close();
		writer.close();
		
	}
	
	public static String fixNumber(String number) {
		if (number.length() > 5) {
			return number.substring(0, 5).replace(".", ",");
		}
		return number.replace(".", ",");
	}

}
